package com.jason.order.service.impl;

import com.jason.common.dao.SequenceMapper;
import com.jason.common.dao.entity.Sequence;
import com.jason.common.error.BusinessErrorEnum;
import com.jason.common.error.BusinessException;
import com.jason.item.dao.ItemMapper;
import com.jason.item.dao.ItemStockMapper;
import com.jason.order.dao.OrderMapper;
import com.jason.item.dao.entity.Item;
import com.jason.order.dao.entity.Order;
import com.jason.order.model.OrderModel;
import com.jason.order.service.OrderService;
import com.jason.um.user.dao.UserMapper;
import com.jason.um.user.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private ItemMapper itemMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ItemStockMapper itemStockMapper;

    @Autowired
    private SequenceMapper sequenceMapper;
    /**
     * 下单
     *
     */
    @Transactional
    @Override
    public Boolean buyItem(OrderModel orderModel) throws BusinessException {
        //数据校验
        Item item = itemMapper.selectByPrimaryKey(orderModel.getItemId());
        if (item == null) {
            throw new BusinessException(BusinessErrorEnum.ITEM_NOT_EXIST);
        }

        User user = userMapper.selectById(orderModel.getUserId());
        if (user == null) {
            throw new BusinessException(BusinessErrorEnum.USER_NOT_EXIST);
        }
        //数量校验
        Integer amount = orderModel.getAmount();
        if (amount == null || amount <= 0 || amount>=99){
            throw new BusinessException(BusinessErrorEnum.PARAM_ILLEGAL_ERROR, "商品数量不合法");
        }

        orderModel.setUnitPrice(item.getPrice());
        orderModel.setTotalPrice(item.getPrice().multiply(new BigDecimal(amount)));
        orderModel.setId(generatorOrderId());
        Order order = orderModel.getOrder();
        // 保存订单
        if (orderMapper.insertSelective(order) <= 0) {
           throw new BusinessException(BusinessErrorEnum.DATABASE_ERROR);
        }
        //减库存
        if (itemStockMapper.decreaseItemStock(item.getId(), amount) <= 0){
            throw new BusinessException(BusinessErrorEnum.STOCK_NOT_ENOUGH);
        }
        // 加销量
        if (itemMapper.increaseItemSales(item.getId(), amount) <= 0){
            throw new BusinessException(BusinessErrorEnum.DATABASE_ERROR);
        }
        return true ;
    }


    /**
     * 新开一个事务单独处理序列
     * @return
     * @throws BusinessException
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public String generatorOrderId() throws BusinessException {
        final String ORDER_SEQ_NAME = "order_seq";
        // 订单id有16位构成
        StringBuilder sb = new StringBuilder();
        // 前6位是时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyMMdd");
        String format = simpleDateFormat.format(new Date());
        sb.append(format);
        // 中间8为是递增编号
        Sequence orderSeq = sequenceMapper.selectByPrimaryKey(ORDER_SEQ_NAME);

        String value= String.format("%08d", orderSeq.getValue());
        sequenceMapper.increaseSequence(ORDER_SEQ_NAME);
        sb.append(value);
        // 最后两位是分库分表位(先默认为00)
        sb.append("00");
        return sb.toString();
    }


}
